package com.yh.ldzl.controller;

import java.util.List;
import java.io.IOException;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.RemoteScTaskService;
import com.ruoyi.system.api.domain.ScTaskDto;
import com.yh.ldzl.domain.QcIpqcLine;
import com.yh.ldzl.service.QualityCheckWebSocketService;

import com.yh.ldzl.service.IQcIpqcLineService;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.yh.ldzl.domain.QcIpqc;
import com.yh.ldzl.service.IQcIpqcService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * 过程检验单Controller
 * 
 * @author yanghuai
 * @date 2025-07-07
 */
@RestController
@RequestMapping("/ipqc")
public class QcIpqcController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(QcIpqcController.class);

    @Autowired
    private IQcIpqcService qcIpqcService;

    @Autowired
    private IQcIpqcLineService qcIpqcLineService;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Resource
    private RemoteScTaskService remoteScTaskService;
    
    @Autowired
    private QualityCheckWebSocketService webSocketService;

    private static final String MESSAGE_TYPE_HEADER = "message_type";
    private static final String MESSAGE_TYPE_QC_IPQC = "qc_ipqc";



    /**
     * 初始化检查
     */
    @PostConstruct
    public void init() {
        if (webSocketService == null) {
            logger.warn("警告: QualityCheckWebSocketService未正常注入，WebSocket通知功能将无法使用");
        } else {
            logger.info("QualityCheckWebSocketService注入成功，WebSocket通知功能已启用");
        }
    }

    /**
     * 查询过程检验单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(QcIpqc qcIpqc)
    {
        startPage();
        List<QcIpqc> list = qcIpqcService.selectQcIpqcList(qcIpqc);
        return getDataTable(list);
    }

    /**
     * 导出过程检验单列表
     */
    @Log(title = "过程检验单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QcIpqc qcIpqc)
    {
        List<QcIpqc> list = qcIpqcService.selectQcIpqcList(qcIpqc);
        ExcelUtil<QcIpqc> util = new ExcelUtil<QcIpqc>(QcIpqc.class);
        util.exportExcel(response, list, "过程检验单数据");
    }

    /**
     * 获取过程检验单详细信息
     */
    @GetMapping(value = "/{ipqcId}")
    public AjaxResult getInfo(@PathVariable("ipqcId") Long ipqcId)
    {
        return success(qcIpqcService.selectQcIpqcByIpqcId(ipqcId));
    }

    /**
     * 新增过程检验单
     */
    @Log(title = "过程检验单", businessType = BusinessType.INSERT)
    @PostMapping("/addIpqc")
    public AjaxResult add(@RequestBody QcIpqc qcIpqc)
    {
        try {
            int result = qcIpqcService.insertQcIpqc(qcIpqc);
            if (result <= 0) {
                return AjaxResult.error("新增QC检测单失败");
            }

            Long ipqcId = qcIpqc.getIpqcId();
            System.out.println("ipqcId:" + ipqcId + ", 准备发送消息");

            // 创建消息关联ID
            String correlationId = "qc-ipqcId-" + ipqcId + "-" + System.currentTimeMillis();
            CorrelationData correlationData = new CorrelationData(correlationId);

            // 创建消息头部，设置消息类型
            MessagePostProcessor messagePostProcessor = message -> {
                MessageProperties properties = message.getMessageProperties();
                properties.setHeader(MESSAGE_TYPE_HEADER, MESSAGE_TYPE_QC_IPQC);
                return message;
            };

            // 发送消息，使用correlationData跟踪，
            rabbitTemplate.convertAndSend(
                    "myExchange",
                    "myRoutingKey",
                    qcIpqc,
                    messagePostProcessor,
                    correlationData
            );

            System.out.println("ipqcId:" + ipqcId + ", 消息已发送, correlationId: " + correlationId + ", messageType: " + MESSAGE_TYPE_QC_IPQC);

            // 添加WebSocket通知
            try {
                webSocketService.pushQualityCheckCreated(
                    ipqcId,
                    qcIpqc.getIpqcCode(),
                    "2", // 过程检验对应inspectionType为2
                    "新的过程检验单已创建: " + qcIpqc.getIpqcName()
                );
                logger.info("WebSocket通知已发送 - 过程检验单创建: ID={}, 编码={}", ipqcId, qcIpqc.getIpqcCode());
            } catch (Exception wsEx) {
                logger.error("发送WebSocket通知失败", wsEx);
                // 即使WebSocket通知失败，也不影响主要业务流程
            }

            return AjaxResult.success("新增QC检测单成功，消息已发送");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送消息异常: " + e.getMessage());
            return AjaxResult.error("操作异常: " + e.getMessage());
        }
    }

    /**
     * 修改过程检验单
     */
    @Log(title = "过程检验单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody QcIpqc qcIpqc)
    {
        int rows = qcIpqcService.updateQcIpqc(qcIpqc);
        if (rows > 0) {
            try {
                // 发送WebSocket通知
                webSocketService.pushQualityCheckUpdated(
                    qcIpqc.getIpqcId(),
                    qcIpqc.getIpqcCode(),
                    "2", // 过程检验对应inspectionType为2
                    "过程检验单已更新: " + qcIpqc.getIpqcName()
                );
                logger.info("WebSocket通知已发送 - 过程检验单更新: ID={}, 编码={}", qcIpqc.getIpqcId(), qcIpqc.getIpqcCode());
            } catch (Exception wsEx) {
                logger.error("发送WebSocket通知失败", wsEx);
                // 即使WebSocket通知失败，也不影响主要业务流程
            }
        }
        return toAjax(rows);
    }

    /**
     * 删除过程检验单
     */
    @Log(title = "过程检验单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ipqcIds}")
    public AjaxResult remove(@PathVariable Long[] ipqcIds)
    {
        return toAjax(qcIpqcService.deleteQcIpqcByIpqcIds(ipqcIds));
    }

    /**
     * 校验过程检验单编码唯一性
     */
    @Log(title = "过程检验单", businessType = BusinessType.EXPORT)
    @GetMapping("/selectQcIpqcCodeUnique/{ipqcCode}")
    public boolean selectQcIpqcCodeUnique(@PathVariable("ipqcCode") String ipqcCode)
    {
        return qcIpqcService.selectQcIpqcCodeUnique(ipqcCode);}

    /**
     * 校验过程检验单名称唯一性
     */
    @Log(title = "过程检验单", businessType = BusinessType.EXPORT)
    @GetMapping("/selectQcIpqcNameUnique/{ipqcName}")
    public boolean selectQcIpqcNameUnique(@PathVariable("ipqcName") String ipqcName)
    {
        return  qcIpqcService.selectQcIpqcNameUnique(ipqcName);
    }
    /**
     * 获取过程检验单关联检测项列表
     */
    @Log(title = "过程检验单", businessType = BusinessType.EXPORT)
    @GetMapping("/selectQcIpqcLineList/{ipqcId}")
    public TableDataInfo selectQcIpqcLineList(QcIpqcLine qcIpqcLine)
        {
            System.out.println("qcIpqcLine:"+qcIpqcLine);
        startPage();
        List<QcIpqcLine> list = qcIpqcLineService.selectQcIpqcLineList(qcIpqcLine);
        return getDataTable(list);
    }
    /**
     * 新增过程检验单关联检测项
     */
    @Log(title = "过程检验单", businessType = BusinessType.INSERT)
    @PostMapping("/insertQcIpqcLine")
    public AjaxResult insertQcIpqcLine(@RequestBody QcIpqcLine qcIpqcLine)
    {
        return toAjax(qcIpqcLineService.insertQcIpqcLine(qcIpqcLine));
    }
    /**
     * 修改过程检验单关联检测项
     */
    @Log(title = "过程检验单", businessType = BusinessType.UPDATE)
    @PutMapping("/updateQcIpqcLine")
    public AjaxResult updateQcIpqcLine(@RequestBody QcIpqcLine qcIpqcLine)
        {
        return toAjax(qcIpqcLineService.updateQcIpqcLine(qcIpqcLine));
    }
    /**
     * 删除过程检验单关联检测项
     */
    @Log(title = "过程检验单", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteQcIpqcLine/{lineIds}")
    public AjaxResult deleteQcIpqcLine(@PathVariable Long[] lineIds)
        {
        return toAjax(qcIpqcLineService.deleteQcIpqcLineByLineIds(lineIds));
    }
    @GetMapping("/qc-query/all-tasks")
    public R<List<ScTaskDto>> getTaskListForQc(
            @RequestParam(value = "workOrderCode", required = false) String workOrderCode,
            @RequestParam(value = "workOrderName", required = false) String workOrderName,
            @RequestParam(value = "processCode", required = false) String processCode,
            @RequestParam(value = "taskName", required = false) String taskName,
            @RequestParam(value = "taskCode", required = false) String taskCode,
            @RequestParam(value = "status", required = false) String status,
            @RequestHeader(value = SecurityConstants.FROM_SOURCE , required = false) String source){
            source="ldzl-qc";
            return remoteScTaskService.getTaskListForQc(workOrderCode, workOrderName, processCode, taskName, taskCode, status, source);
    }
    @GetMapping("/selectQcIpqcProductInfo")
    public Map<String, Object> selectQcIpqcProductInfo(@RequestParam("work_order_task_id") Long work_order_task_id) {
        return qcIpqcService.selectQcIpqcProductInfo(work_order_task_id);
    }


}
